const { Client } = require('dataflare-client');

// Get API URL and key from environment variables
const apiUrl = process.env.DATAFLARE_API_URL || 'http://localhost:8080';
const apiKey = process.env.DATAFLARE_API_KEY || '';

// Create client
const client = new Client(apiUrl, {
  apiKey,
  timeout: 30000,
});

// Create and run workflow
async function createAndRunWorkflow() {
  try {
    // Create workflow
    const workflow = await client.createWorkflow({
      name: 'example-workflow',
      description: 'Example workflow',
      definition: `
version: "1.0"
name: "example-workflow"
description: "Example workflow"
config:
  mode: "stream"
  execution:
    engine: "actor"
    parallelism: 1
  state:
    backend: "memory"
schemas:
  record:
    fields:
      id:
        type: "string"
        required: true
      value:
        type: "number"
        description: "Value"
sources:
  memory_source:
    type: "memory"
    schema: "record"
    config:
      data: [
        {"id": "1", "value": 10},
        {"id": "2", "value": 20},
        {"id": "3", "value": 30}
      ]
    description: "In-memory data source"
sinks:
  console_sink:
    type: "console"
    schema: "record"
    config:
      format: "json"
    description: "Console output sink"
nodes:
  process:
    type: "transform"
    description: "Process input records"
    inputs:
      default:
        schema: "record"
    outputs:
      default:
        schema: "record"
    transform:
      language: "javascript"
      code: |
        function process(record) {
          return {
            id: record.id,
            value: record.value * 2
          };
        }
edges:
  - from:
      source: "memory_source"
    to:
      node: "process"
      input: "default"
  - from:
      node: "process"
      output: "default"
    to:
      sink: "console_sink"
`,
    });

    console.log(`Created workflow: ${workflow.id}`);

    // Run workflow
    const run = await client.runWorkflow(workflow.id, {
      parameters: {
        param1: 'value1',
      },
    });

    console.log(`Started workflow run: ${run.id}`);

    // Wait for workflow to complete
    try {
      const completedRun = await client.waitForWorkflowRun(workflow.id, run.id, {
        timeout: 60000,
        pollInterval: 1000,
      });

      console.log(`Workflow run completed with status: ${completedRun.status}`);
      if (completedRun.error) {
        console.log(`Error: ${completedRun.error}`);
      }
    } catch (error) {
      if (error.message.includes('did not complete in time')) {
        console.log('Workflow run timed out');
        // Cancel the run
        await client.cancelWorkflowRun(workflow.id, run.id);
        console.log(`Cancelled workflow run: ${run.id}`);
      } else {
        throw error;
      }
    }

    // List workflow runs
    const runs = await client.listWorkflowRuns(workflow.id, {
      limit: 10,
    });

    console.log('Workflow runs:');
    for (const run of runs.runs) {
      console.log(`- ${run.id}: ${run.status}`);
    }

    // Delete workflow
    await client.deleteWorkflow(workflow.id);
    console.log(`Deleted workflow: ${workflow.id}`);
  } catch (error) {
    console.error(`Error: ${error.message}`);
    if (error.code) {
      console.error(`Code: ${error.code}`);
    }
    if (error.status) {
      console.error(`Status: ${error.status}`);
    }
    process.exit(1);
  }
}

// Run the example
createAndRunWorkflow();
